package com.easybuilder.core.function.service.impl;


import com.easybuilder.common.utils.StringUtil;
import com.easybuilder.core.function.dao.SysFunctionDao;
import com.easybuilder.core.function.entity.*;
import com.easybuilder.core.function.service.*;
import com.easybuilder.core.table.entity.SysTableInfo;
import com.easybuilder.core.table.service.TableInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class SysFunctionServiceImpl implements SysFunctionService {

    @Autowired
    private SysFunctionDao sysFunctionDao;
    @Autowired
    private SysGridService sysGridService;
    @Autowired
    private SysGridItemService gridItemService;
    @Autowired
    private TableInfoService tableInfoService;
    @Autowired
    private SysFormService formService;
    @Autowired
    private SysFormItemService formItemService;

    @Override
    public int insertSelective(SysFunction sysFunction) {
        return sysFunctionDao.insertSelective(sysFunction);
    }

    @Override
    public int updateSelective(SysFunction sysFunction) {

        return sysFunctionDao.updateByPrimaryKeySelective(sysFunction);
    }

    /** 保存功能 */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean save(SysFunction sysFunction) {
        // 1.判断功能是否存在
        Long id = sysFunction.getId();
        // 如果功能不存在，执行插入
        if (id == null) {
            // 插入功能表
            int insert = sysFunctionDao.insertSelective(sysFunction);
            // 如果插入功能表成功，新增列表、列表项、表单等数据
            if (insert > 0) {
                // 根据table_id，查询tableInfo数据
                List<SysTableInfo> tableInfos = tableInfoService.selectByTableId(sysFunction.getTableId());
                // 添加列表和列表项
                addGridAndItem(sysFunction, tableInfos);
                // 添加表单和表单项
                addFormAndItem(sysFunction, tableInfos);
            }
        } else { // 如果功能存在，执行更新操作
            // 根据功能id，查询未更新之前的功能
            SysFunction oldFunction = new SysFunction();
            oldFunction.setId(sysFunction.getId());
            oldFunction = sysFunctionDao.selectByPrimaryKey(oldFunction);
            // 更新功能表
            int update = sysFunctionDao.updateByPrimaryKeySelective(sysFunction);
            if (update > 0) {
                // 更新列表和列表项
                updateGridAndItem(sysFunction, oldFunction);
                // 更新表单和表单项
                updateFormAndItem(sysFunction, oldFunction);
            }

        }
        return false;
    }


    /** 添加列表主表和列表项 */
    private void addGridAndItem(SysFunction sysFunction, List<SysTableInfo> tableInfos) {
        // 新增grid主表数据
        SysGrid sysGrid = new SysGrid();
        sysGrid.setGridName(sysFunction.getFunctionName());
        sysGrid.setGridCode(sysFunction.getFunctionCode());
        sysGrid.setTableId(sysFunction.getTableId());
        int insertGrid = sysGridService.insertSelective(sysGrid);
        if (insertGrid > 0) {
            tableInfos.forEach(tableInfo -> {
                // 表字段名
                String columnName = tableInfo.getColumnName();
                // 字段描述
                String comment = tableInfo.getComment();
                SysGridItem gridItem = new SysGridItem();
                gridItem.setGridId(sysGrid.getId());
                gridItem.setLabel(comment);
                gridItem.setProp(StringUtil.column2Field(columnName));
                gridItem.setSort(tableInfo.getSort());
                gridItem.setWidth(80);
                gridItem.setAlign("center");
                gridItem.setFontColor("#000");
                gridItem.setBackgroundColor("#fff");
                // 是否隐藏，如果是系统字段，默认隐藏
                gridItem.setHide(tableInfo.getSystem());
                gridItemService.insertSelective(gridItem);
            });
        }
    }

    /** 添加表单主表和表单项 */
    private void addFormAndItem(SysFunction sysFunction, List<SysTableInfo> tableInfos) {
        // 新增表单主表
        SysForm sysForm = new SysForm();
        sysForm.setFormName(sysFunction.getFunctionName());
        sysForm.setFormCode(sysFunction.getFunctionCode());
        sysForm.setTableId(sysFunction.getTableId());
        int insertForm = formService.insertSelective(sysForm);
        // 表单主表新增成功后，新增表单子表项
        if (insertForm > 0) {
            tableInfos.forEach(tableInfo -> {
                // 表字段名
                String columnName = tableInfo.getColumnName();
                // 字段描述
                String comment = tableInfo.getComment();
                SysFormItem formItem = new SysFormItem();
                formItem.setFormId(sysForm.getId());
                formItem.setLabel(comment);
                formItem.setName(StringUtil.column2Field(columnName));
                formItem.setSort(tableInfo.getSort());
                formItem.setWidth(100);
                formItem.setRequired(0);
                // 是否启用，默认未启用
                formItem.setStatus(0);
                formItemService.insertSelective(formItem);
            });
        }
    }

    /** 更新列表和列表项 */
    private void updateGridAndItem(SysFunction sysFunction, SysFunction oldFunction) {
        // 如果功能选择的表发生了变化
        if (!oldFunction.getTableId().equals(sysFunction.getTableId())) {
            SysGrid sysGrid = new SysGrid();
            sysGrid.setTableId(oldFunction.getTableId());
            sysGrid = sysGridService.selectOne(sysGrid);
            // 删除旧表列表主表数据
            sysGridService.deleteByExample(sysGrid);
            // 删除旧表列表项数据
            Example example = new Example(SysGridItem.class);
            example.createCriteria().andEqualTo("gridId", sysGrid.getId());
            gridItemService.deleteByExample(example);
            // 查询tableInfo
            List<SysTableInfo> sysTableInfos = tableInfoService.selectByTableId(sysFunction.getTableId());
            // 新增列表主表和表单项
            addGridAndItem(sysFunction, sysTableInfos);
        }
    }

    /** 更新表单和表单项 */
    private void updateFormAndItem(SysFunction sysFunction, SysFunction oldFunction) {
        // 如果功能选择的表发生了变化
        if (!oldFunction.getTableId().equals(sysFunction.getTableId())) {
            SysForm sysForm = new SysForm();
            sysForm.setTableId(oldFunction.getTableId());
            sysForm = formService.selectOne(sysForm);
            // 删除旧表表单主表数据
            sysGridService.deleteByExample(sysForm);
            // 删除旧表表单项项数据
            Example example = new Example(SysForm.class);
            example.createCriteria().andEqualTo("formId", sysForm.getId());
            formItemService.deleteByExample(example);
            // 查询tableInfo
            List<SysTableInfo> sysTableInfos = tableInfoService.selectByTableId(sysFunction.getTableId());
            // 新增表单主表和表单项
            addFormAndItem(sysFunction, sysTableInfos);
        }
    }

}
